import { Injectable } from '@angular/core';
import { LoadingController, ToastController } from 'ionic-angular';
import { CookieService } from 'ngx-cookie';

import { SecurityDataService } from './SecurityDataService';
import { BaseService } from '../data/BaseService';

// 登录服务
@Injectable()
export class SecurityService {

	// 当前用户
	public user={};
	
	// 应用服务权限
	public si={};

	// 菜单权限
	public mi={};

	/**
	 * 显示消息
	 */
	public showMessage=true;

	constructor(
		private _cookieService:CookieService,
		private loadingCtrl: LoadingController,
		private toastCtrl: ToastController,
		private securityDataService:SecurityDataService,
		private baseService:BaseService,
		) { 
	}

	// 初始化
	init(){
		// 查询一下，看是不是有用户登录过
		this.getUserInfo(null, ()=>{
			// 查询一下tgt是否存在
			let tgt:string = this._cookieService.get("jwt");
			if(tgt) this.innerLogin(tgt);
		});
	}

	// 获取当前用户信息
	getUserInfo(suc?:Function,fai?:Function){
		this.securityDataService.getUserInfo().subscribe((ud)=>{
			if(ud && ud.user){
				this.user = ud.user;
				if (ud.services) {
					//this.si=new Object();
					let temp={};
					ud.services.forEach(function (e) {
						temp[e]=true;
						console.log(e);
					});
					this.si =temp;
				}
				if (ud.menus) {
					this.mi=new Object();
					let temp={};
					ud.menus.forEach(function (e) {
						temp[e]=true;
					});
					this.mi = temp;
				}
				if(suc) suc();
			} else {
				this.user = {};
				this.mi={};
				this.si={};
				if(fai) fai();
			}
		});
	}

	// 系统登录
	login(username:string, password:string, logined?:Function):void{
		if(!username || username==null || username===''){
			if(this.showMessage){
				this.toastCtrl.create({
					message: '用户名不能为空！',
					duration: 2000,
					position: 'bottom'
				}).present();
			}
			
			return;
		}

		if(!password || password==null || password===''){
			if(this.showMessage){
				this.toastCtrl.create({
					message: '密码不能为空！',
					duration: 2000,
					position: 'bottom'
				}).present();
			}
			return;
		}

		let loader = this.loadingCtrl.create({
	      	content: "登录中..."
	    });
	    loader.present();
		this._cookieService.removeAll();
		// 创建tgt
		this.securityDataService.loginAjax(username,password).subscribe(
			(td)=>{
				if(!td.ok){
					loader.dismiss();
					if(this.showMessage){
						this.toastCtrl.create({
							message: '用户密码错误！',
							duration: 2000,
							position: 'bottom'
						}).present();
					}
				    return;
				}

				let tgt = td.ok;
				// tgt保存120分钟
				let cDate:Date = new Date();
    			cDate.setMinutes(cDate.getMinutes() + 120, cDate.getSeconds(), 0);
				this._cookieService.put("SSO_TGT", tgt, {expires:cDate});
				this.innerLogin(tgt,loader,logined);
			}
		);
	}

	private innerLogin(tgt:string,loader?:any,logined?:Function){
		// 创建st
		let service = this.baseService.service;
		this.securityDataService.serviceTicketsAjax(tgt,service).subscribe((sd)=>{
			if(!sd.ok){
				if(loader) loader.dismiss();
				if(this.showMessage){
					this.toastCtrl.create({
						message: '用户密码错误！',
						duration: 2000,
						position: 'bottom'
					}).present();
				}
			    return;
			}
		
			let ticket = sd.ok;
			// 模拟登录
			this.securityDataService.mklogin(ticket).subscribe((jsd)=>{
				if(loader) loader.dismiss();
				if(jsd){
					// 获取当前用户
					let cDate:Date = new Date();
    				cDate.setMinutes(cDate.getMinutes() + 120, cDate.getSeconds(), 0);
					this._cookieService.put("jwt", jsd.jwt, {expires:cDate});
					this.getUserInfo(logined);
				} else {
					if(this.showMessage){
						this.toastCtrl.create({
							message: '用户密码错误！',
							duration: 2000,
							position: 'bottom'
						}).present();
					}
				}
			});
		});
	}

	// 系统退出
	logout(){
		let loader = this.loadingCtrl.create({
	      	content: "退出中..."
	    });
	    loader.present();
		this.securityDataService.loginOut().subscribe(()=>{
			this.user = null;
			this._cookieService.removeAll();
			loader.dismiss();
			window.localStorage.setItem('bhqoa_initLogin',"false");
		});
	}

	isPoneAvailable(str):boolean{  
        var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
        return myreg.test(str);
    }

	// 用户注册信息
	userRegister(ac:string,pw:string,rpw:string,registed?:Function):void{
		if(!ac || ac==null || ac===''){
			this.toastCtrl.create({
		        message: '用户名不能为空！',
		        duration: 2000,
		        position: 'bottom'
		    }).present();
			return;
		}
		if(!this.isPoneAvailable(ac)){
			this.toastCtrl.create({
		        message: '请输入正确的手机号码！',
		        duration: 2000,
		        position: 'bottom'
		    }).present();
			return;
		}

		if(!pw || pw==null || pw===''
			|| !rpw || rpw==null || rpw===''
			|| pw!=rpw){
			this.toastCtrl.create({
		        message: '密码为空，或不一至！',
		        duration: 2000,
		        position: 'bottom'
		    }).present();
			return;
		}

		if(pw.length<6){
			this.toastCtrl.create({
		        message: '密码长度不能少于6位！',
		        duration: 2000,
		        position: 'bottom'
		    }).present();
			return;
		}

		let loader = this.loadingCtrl.create({
	      	content: "注册中..."
	    });
	    loader.present();
		this.securityDataService.userRegister(ac,pw,rpw).subscribe((ok)=>{
			// 注册成功，就登录
			if(ok==true){
				loader.dismiss();
				this.login(ac, pw, registed);
			}else{
				this.toastCtrl.create({
			        message: '注册失败：帐号已存在！',
			        duration: 2000,
			        position: 'bottom'
			    }).present();
				loader.dismiss();
			}
		});
	}

	// 设置当前密码
	setPassword(pw:string,rpw:string,success?:Function):void{
		if(!pw || pw==null || pw===''
			|| !rpw || rpw==null || rpw===''
			|| pw!=rpw){
			this.toastCtrl.create({
		        message: '密码为空，或不一至！',
		        duration: 2000,
		        position: 'bottom'
		    }).present();
			return;
		}

		let loader = this.loadingCtrl.create({
	      	content: "设置中..."
	    });
	    loader.present();
		this.securityDataService.setPassword(pw,rpw).subscribe((ok)=>{
			// 修改成功
			if(ok==true){
				loader.dismiss();
				if(success) success();
			}else{
				this.toastCtrl.create({
			        message: '设置失败，请重新登录系统后重试！',
			        duration: 2000,
			        position: 'bottom'
			    }).present();
				loader.dismiss();
			}
		});
	}
}